package com.yunpuvip.sachet.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunpuvip.sachet.biz.entity.BalanceHistory;
import com.yunpuvip.sachet.biz.entity.Order;
import com.yunpuvip.sachet.biz.entity.Payment;
import com.yunpuvip.sachet.biz.entity.Player;
import com.yunpuvip.sachet.biz.mapper.BalanceHistoryMapper;
import com.yunpuvip.sachet.biz.model.params.BalanceHistoryParam;
import com.yunpuvip.sachet.biz.model.result.BalanceHistoryResult;
import  com.yunpuvip.sachet.biz.service.BalanceHistoryService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunpuvip.sachet.biz.service.PlayerService;
import com.yunpuvip.sachet.biz.service.SysparamService;
import com.yunpuvip.sachet.modular.constant.ApplicationConstant;
import com.yunpuvip.sachet.modular.page.LayuiPageFactory;
import com.yunpuvip.sachet.modular.page.LayuiPageInfo;
import com.yunpuvip.sachet.modular.util.sms.SMSTemplateType;
import com.yunpuvip.sachet.modular.util.sms.Sendsms;
import com.yunpuvip.sachet.modular.vo.rest.request.BalanceReqVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 余额变动历史 服务实现类
 * </p>
 *
 * @author wushaohong
 * @since 2019-08-10
 */
@Service
public class BalanceHistoryServiceImpl extends ServiceImpl<BalanceHistoryMapper, BalanceHistory> implements BalanceHistoryService {

    @Autowired
    private PlayerService playerService;

    @Autowired
    private SysparamService sysparamService;
    @Override
    public void add(BalanceHistoryParam param){
        BalanceHistory entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BalanceHistoryParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BalanceHistoryParam param){
        BalanceHistory oldEntity = getOldEntity(param);
        BalanceHistory newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BalanceHistoryResult findBySpec(BalanceHistoryParam param){
        return null;
    }

    @Override
    public List<BalanceHistoryResult> findListBySpec(BalanceHistoryParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BalanceHistoryParam param){
        Page pageContext = getPageContext();
        Page<BalanceHistory> historypage = baseMapper.getBalanceHistorypage(pageContext, param);
        return LayuiPageFactory.createPageInfo(historypage);
    }

    private Serializable getKey(BalanceHistoryParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BalanceHistory getOldEntity(BalanceHistoryParam param) {
        return this.getById(getKey(param));
    }

    private BalanceHistory getEntity(BalanceHistoryParam param) {
        BalanceHistory entity = new BalanceHistory();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }


    @Override
    public Integer insertAddBanlanceHistory(Payment payment) {
        Integer playerId = payment.getPlayerId();
        Player player = playerService.getPlayer(playerId);
        //该金额在充值时：只包含充值的
        BigDecimal amount = payment.getAmount();

        BigDecimal gitAmount = payment.getGiftAmount();
        BigDecimal total = amount.add(gitAmount);

        BigDecimal balance = player.getBalance();
        BalanceHistory history = new BalanceHistory();
        BigDecimal add = balance.add(total);
        history.setBalanceAfter(add);
        history.setBalanceBefore(balance);
        history.setChangeBalance(total);
        history.setPlayerId(playerId);
        history.setGiftAmount(gitAmount);
        history.setPaymentId(payment.getId());
        history.setPaymentNo(payment.getOrderNo());
        history.setReason("充值");
        player.setBalance(add);
        playerService.updateById(player);
        String phone = player.getPhone();
        //发送短信
        String s = amount.setScale(2).toString();
        HashMap<String, String> map = new HashMap<>();
        map.put("name",player.getNickname());
        map.put("amount",total.setScale(2).toString());
        map.put("balance",add.setScale(2).toString());
        String prettyStr = JSONUtil.toJsonPrettyStr(map);

        Sendsms.sendSmsRechargeMsg(phone,prettyStr, SMSTemplateType.RECHARGE.getCode());
        return  baseMapper.insert(history);
    }

    @Override
    public Integer insertSubBanlanceHistoryAndSubPlayerBalance(BigDecimal sub, Integer playerId,Payment payment) {
        Player player = playerService.getPlayer(playerId);

        BigDecimal balance = player.getBalance();
        if(balance.compareTo(sub)<0){
            //余额不足返回-1
            return -1;
        }
        //修改账户余额
        player.setBalance(balance.subtract(sub));
        playerService.updateById(player);
        BalanceHistory history = new BalanceHistory();
        BigDecimal add = balance.subtract(sub);
        history.setBalanceAfter(add);
        history.setBalanceBefore(balance);
        history.setPlayerId(playerId);
        history.setChangeBalance(sub);
        history.setPaymentId(payment.getId());
        history.setPaymentNo(payment.getOrderNo());
        history.setReason("订单支付");
        //发送短信
        String s = sub.setScale(2).toString();
        HashMap<String, String> map = new HashMap<>();
        map.put("name",player.getNickname());
        map.put("amount",sub.setScale(2).toString());
        map.put("balance",add.setScale(2).toString());
        String prettyStr = JSONUtil.toJsonPrettyStr(map);
        Sendsms.sendSmsRechargeMsg(player.getPhone(),prettyStr, SMSTemplateType.COMSUME.getCode());
        return  baseMapper.insert(history);
    }
        @Override
        public IPage<BalanceHistory> getBalancePage(BalanceReqVo balanceReqVo) {
            Integer day = balanceReqVo.getDay();
            DateTime dateTime = DateUtil.offsetDay(new Date(),-1*day);
            Integer playerId = balanceReqVo.getPlayerId();
            Page pageContext = getPageContext();
            LambdaQueryWrapper<BalanceHistory> lambda = new QueryWrapper<BalanceHistory>().lambda();
            lambda.eq(BalanceHistory::getPlayerId,playerId);
            if(day>0) {
                lambda.ge(BalanceHistory::getCreateTime, dateTime);
            }
            lambda.orderByDesc(BalanceHistory::getCreateTime);

            IPage page = this.page(pageContext, lambda);
            return page;
        }

    @Override
    public boolean DrawBackaAndAddBanlanceHistory(Order order) {
        Integer playerId = order.getPlayerId();
        Player player = playerService.getPlayer(playerId);
        BigDecimal add = player.getBalance().add(order.getPayBalance());
        BalanceHistory balanceHistory = new BalanceHistory();
        balanceHistory.setReason("余额退还");
        balanceHistory.setBalanceAfter(add);
        balanceHistory.setBalanceBefore(player.getBalance());
        balanceHistory.setPlayerId(playerId);
        baseMapper.insert(balanceHistory);
        player.setBalance(add);
        playerService.updateById(player);
        return false;
    }


}
